#!/bin/bash

# Make sure only root can run our script
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
NAME="agency_im"

# 语言环境
echo "LC_ALL=zh_CN.UTF-8" >> /etc/environment
echo "zh_CN.UTF-8 UTF-8" >> /etc/locale.gen
echo "LANG=zh_CN.UTF-8" > /etc/locale.conf
locale-gen zh_CN.UTF-8
export LC_ALL="zh_CN.UTF-8"

# 二进制依赖/工具
apt update
apt install -y python-dev libmysqlclient-dev supervisor libcurl4-gnutls-dev libgnutls-dev python-pip libffi-dev git screen
# 创建ubuntu用户
mkdir -p /home/ubuntu
if ! (id ubuntu >/dev/null 2>&1); then
    useradd -r ubuntu
fi
chown ubuntu:ubuntu /home/ubuntu
# 全局安装python依赖
pip install -r $DIR/requirement.txt
pip install ipython==5.6.0

# logrotate&supervisor的配置
cp $DIR/supervisor.conf /etc/supervisor/conf.d/$NAME.conf
sed -i '/\[supervisord\]/a minfds=65535' /etc/supervisor/supervisord.conf
systemctl enable supervisor
supervisorctl restart
cp $DIR/logrotate /etc/logrotate.d/$NAME
chown root /etc/logrotate.d/$NAME

# golang调试相关，也可以不装
wget https://dl.google.com/go/go1.11.4.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.11.4.linux-amd64.tar.gz
echo "PATH=$PATH:/usr/local/go/bin" >> /home/ubuntu/.bashrc
source "/home/ubuntu/.bashrc"
go get -u github.com/derekparker/delve/cmd/dlv

# 修改最大连接数和文件描述符限制
echo "* - noproc 11000" >> /etc/security/limits.conf
echo "root soft nofile 65534" >>  /etc/security/limits.conf
echo "root hard nofile 65534" >> /etc/security/limits.conf
echo "* hard nofile 65534" >> /etc/security/limits.conf
echo "* soft nofile 65534" >> /etc/security/limits.conf
echo "net.core.somaxconn=4096" >> /etc/sysctl.conf
sysctl -p

echo "Done!"
